<?php
/**
 * Template
 *
 * Automatically render and output a template using the 
 * $controller/$action.tpl.php file.
 *
 * = Grab a template plugin object =
 *
 *    $template = Spaph->getInstance()->getPlugin('Template');
 *
 * = Register filter plugins =
 *
 *    $template->add_filters('wrapper','fancyFilter')
 *
 * = Populate template =
 *
 *    $template->add(array('fname' => 'henry', 'lname' => 'george'));
 *    $template->add('greeting', 'hello')
 *
 * = Turn it off otherwise it might complain about missing templates.
 *
 *    $template->off()
 */
class Template extends Spaph_Plugin
{
    private $__PROPS = array('on' => null, 
                             'filters' => array(),
                             'view' => null);

    public function __construct()
    {
        $this->off(); // This is how to turn it off
        $this->on();  // On by default
    }

    public function __set($name, $value)
    {
        $this->__PROPS['view']->$name = $value;
    }

    public function _preDispatch()
    {
        $this->__PROPS['view'] = new Spaph_View($this->__PROPS['filters']);
    }

    /**
     * Accessor. Get the Spaph_View properties.
     *
     * @return mix
     */
    public function get($name)
    {
        return $this->__PROPS['view']->$name;
    }

    public function _postDispatch()
    {
        if(! $this->__PROPS['on'])
            return;

        list($action,$controller) = Spaph::getInstance()->getAction();
        $file = $controller.'/'.$action.'.tpl.php';
        $this->__PROPS['view']->output($file);
    }
    
    public function add_filters()
    {
        $tmp = array();
        for($i = 0 ; $i < func_num_args(); $i++) {
            $this->__PROPS['filters'][] = is_object(func_get_arg($i)) ? func_get_arg($i) : Spaph::getInstance()->getPlugin(func_get_arg($i));
        }
    }
    
    public function off()
    {
        $this->__PROPS['on'] = false;
    }
    
    public function on()
    {
        $this->__PROPS['on'] = true;
    }
}

